package com.dfd.store.web.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dfd.store.domain.Cart;
import com.dfd.store.domain.CartItem;
import com.dfd.store.domain.Product;
import com.dfd.store.service.ProductService;
import com.dfd.store.service.impl.ProductServiceImpl;
import com.dfd.store.web.base.BaseServlet;

public class CartServlet extends BaseServlet {

	// 添加购物项到购物车
	public String addCartItemToCart(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		// 从session获取购物车
		Cart cart = (Cart) req.getSession().getAttribute("cart");
		if (null == cart) {
			// 如果获取不到,创建购物车对象,放在session中
			cart = new Cart();
			req.getSession().setAttribute("cart", cart);
		}
		// 如果获取到,使用即可
		// 获取到商品id,数量
		String pid = req.getParameter("pid");
		int num = Integer.parseInt(req.getParameter("quantity"));
		// 通过商品id查询都商品对象
		ProductService ProductService = new ProductServiceImpl();
		Product product = ProductService.findProductById(pid);
		// 获取到待购买的购物项
		CartItem cartItem = new CartItem();
		cartItem.setNum(num);
		cartItem.setProduct(product);

		// 调用购物车上的方法
		cart.addCartItemToCar(cartItem);

		// 重定向到/jsp/cart.jsp
		resp.sendRedirect("/Store/jsp/cart.jsp");
		// return "/jsp/cart.jsp";
		return null;
	}

	/**
	 * 清除购物项
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	public String removeCartItem(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String pid = req.getParameter("pid");
		Cart cart = (Cart) req.getSession().getAttribute("cart");
		cart.removeCartItem(pid);
		resp.sendRedirect("/Store/jsp/cart.jsp");
		return null;
	}

	/**
	 * 清除全部
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	public String clearCart(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		Cart cart = (Cart) req.getSession().getAttribute("cart");
		cart.clearCart();
		resp.sendRedirect("/Store/jsp/cart.jsp");
		return null;
	}
}
